//------------------------------------------------------------------------------
//
// ...
// class: ClientDataDisplayer 
// author: 喵大斯( as3er.net )
// created: 2015/8/24
// copyright (c) 2015 喵大斯( aosnow@yeah.net )
//
//------------------------------------------------------------------------------

/// <reference path='../core/jquery.d.ts'/>
/// <reference path='../core/jquery.extend.d.ts'/>
/// <reference path='../core/page_core.d.ts'/>
/// <reference path='../core/utils.ts'/>
/// <reference path='../core/pageset.d.ts'/>
/// <reference path='../core/submitter.d.ts'/>
/// <reference path='../core/clienter.d.ts'/>
/// <reference path='consultant_client_quest.d.ts'/>

class ClientData
{
	//--------------------------------------------------------------------------
	//
	// Class constants
	//
	//--------------------------------------------------------------------------

	// 当客户目标被选定并显示时，在目标表格对象上派发此事件
	static SELECTED:string = "client_selected";

	//--------------------------------------------------------------------------
	//
	//  Class constructor
	//
	//--------------------------------------------------------------------------

	/**
	 * 客户资料显示控制器
	 * @param table 用于显示用户资料的表格 JQuery 对象
	 * @param selectabled 是否显示并支持“选择目标客户”按钮
	 * @param editabled 是否显示并支持“编辑客户资料”按钮
	 */
	constructor( table:JQuery, selectabled:boolean = true, editabled:boolean = true )
	{
		this._table = table;
		this.initTable();
		this._selectabled = selectabled;
		this._editabled = editabled;
	}

	//--------------------------------------------------------------------------
	//
	//	Class properties
	//
	//--------------------------------------------------------------------------

	private _table:JQuery;
	private _btnSelector:JQuery;
	private _btnEditor:JQuery;

	private _selectabled:boolean;
	private _editabled:boolean;

	//----------------------------------------
	// clientKey
	//----------------------------------------

	/** 客户 key */
	public clientKey;

	//--------------------------------------------------------------------------
	//
	//	Class methods
	//
	//--------------------------------------------------------------------------

	private initTable():void
	{
		// 显示/隐藏客户详细资料
		var title:JQuery = this._table.find( "tr[rel='title']" );
		title.css( "cursor", "pointer" );
		title.click( ()=>{ this.showOrHideDetailed(); } );
	}

	private setControl( selectabled:boolean = true, editabled:boolean = true ):void
	{
		var nickname:JQuery = $( "#nickname" );
		var container:JQuery = nickname.parent();

		// 客户名称默认值
		nickname.html( "<em class='caption'> - - </em>" );

		// 移除原有的控制按钮
		container.find( "> [id!='nickname']" ).remove();

		// 创建选择目标客户按钮
		if( selectabled )
		{
			container.append( "<a id='btnSelector'>（选择目标客户）</a>" );
			this._btnSelector = container.find( "#btnSelector" );
			this._btnSelector.click( ()=>{ this.selectClientHandler(); } );
		}

		// 创建完善客户资料按钮
		if( editabled )
		{
			container.append( "<a id='btnEditor'>（完善客户资料）</a>" );
			this._btnEditor = container.find( "#btnEditor" );
			this._btnEditor.click( ()=>{ this.editClientHandler(); } );
		}
	}

	/**
	 * 请求刷新当前用户的客户资料
	 */
	public request_client_info()
	{
		if( empty( this.clientKey ) )return;

		submitter.post( "client_info_get.php", { key: this.clientKey }, ( d )=>
		{
			if( d.err == 0 )
			{
				this.setData( d );
			}
			else
			{
				infopad.err( d.msg );
			}
		}, "json" );
	}

	/**
	 * 为无预约类型的接待类型初始化
	 */
	public initTableForWithoutReserve()
	{
		this.resetHtmlContent();
		this.setControl( this._selectabled, this._editabled );
		this.detailed( false );
	}

	/**
	 * 设置数据填充用户资料表
	 * @param data
	 */
	public setData( data:any ):string
	{
		// 客户资料
		if( !empty( data ) )
		{
			// 保存客户 key 值
			if( data.hasOwnProperty( "client" ) )
				this.clientKey = data.client;
			else
				this.clientKey = data.key;

			// 重置 html 内容
			this.resetHtmlContent();
			this.setControl( this._selectabled, this._editabled );
			this.detailed( false );

			var invalid:string = data.invalid == 1 ? "<em class='caption'>（无效客户）</em>" : "<em class='valid'>（有效客户）</em>";

			$( "#nickname" ).html( data.nickname + invalid );
			$( "#category" ).html( this.format( data.categoryns ) );
			$( "#source" ).html( this.format( data.sourcens ) );
			$( "#keyword" ).html( this.format( data.keyword ) );

			var address = data.province + " " + data.city + " （" + data.address + "）";
			$( "#address" ).html( empty( address ) ? "<em class='caption'>未填写</em>" : address );

			$( "#phone" ).html( this.format( data.phone ) );
			$( "#email" ).html( this.format( data.email ) );
			$( "#qq" ).html( this.format( data.qq ) );
			$( "#ip" ).html( this.format( data.ip ) );
			$( "#desc" ).html( this.format( data.desc ) );

			// 设置问卷地址列表
			quest_init( $( "#quest_list" ), $.parseJSON( data.quests ), true );
		}
		else
		{
			this.clientKey = null;

			$( "#nickname" ).html( "&nbsp;" );
			$( "#category" ).html( "&nbsp;" );
			$( "#source" ).html( "&nbsp;" );
			$( "#address" ).html( "&nbsp;" );
			$( "#keyword" ).html( "&nbsp;" );
			$( "#phone" ).html( "&nbsp;" );
			$( "#email" ).html( "&nbsp;" );
			$( "#qq" ).html( "&nbsp;" );
			$( "#ip" ).html( "&nbsp;" );
			$( "#desc" ).html( "&nbsp;" );

			$( "#quest_list" ).html( "&nbsp;" );
		}

		return this.clientKey;
	}

	private format( val:any ):string
	{
		if( empty( val ) )
			return "<em class='caption'>&lt;未填写&gt;</em>";
		else if( val == '--' )
			return "<em class='caption'>&lt;禁止查看&gt;</em>";
		return val;
	}

	private resetHtmlContent():void
	{
		var h = "<tr>";
		h += "<th width=\"25%\">客户姓名/称呼</th>";
		h += "<td width=\"75%\"><span id=\"nickname\" class=\"stress unit hand\"></span></td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>客户来源渠道</th>";
		h += "<td id=\"source\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>关键字</th>";
		h += "<td id=\"keyword\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>客户类别</th>";
		h += "<td id=\"category\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>问卷地址</th>";
		h += "<td colspan=\"3\" id=\"quest_list\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr>";
		h += "<th>所在地</th>";
		h += "<td id=\"address\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr>";
		h += "<th>联系电话</th>";
		h += "<td id=\"phone\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>电子邮箱</th>";
		h += "<td id=\"email\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>QQ</th>";
		h += "<td id=\"qq\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>IP地址</th>";
		h += "<td id=\"ip\">&nbsp;</td>";
		h += "</tr>";
		h += "<tr rel=\"hide\">";
		h += "<th>备注信息</th>";
		h += "<td id=\"desc\">&nbsp;</td>";
		h += "</tr>";

		this._table.find( "tr:not(:first)" ).remove();
		this._table.append( h );
		update_row_bg( this._table );
	}

	//--------------------------------------------------------------------------
	//
	// 表单收起和展开方法
	//
	//--------------------------------------------------------------------------

	/**
	 * 将客户资料表的指定行进行隐藏或者显示
	 * @param show true-显示；false-隐藏
	 * @param rel 行对象的 rel 属性值，用于区分不同的操作需求
	 */
	public detailed( show:boolean, rel:string = 'hide' )
	{
		if( show )
			this._table.find( "tr[rel='hide']" ).show();
		else
			this._table.find( "tr[rel='hide']" ).hide();

		setTableRowBackColor( this._table );
	}

	//--------------------------------------------------------------------------
	//
	//  Event handlers
	//
	//--------------------------------------------------------------------------

	private selectClientHandler()
	{
		clienter.setCallback( ( data )=>{this.clientSelectedHandler( data );} );
		clienter.reset();
		clienter.open();
	}

	private clientSelectedHandler( data:any )
	{
		this.setData( data );
		this._table.triggerHandler( ClientData.SELECTED, data );
	}

	private editClientHandler()
	{
		if( empty( this.clientKey ) )
		{
			infopad.err( "请先指定目标客户，再编辑资料。" );
			return;
		}

		var url = "consultant_client.php?key=" + this.clientKey + "&close=true";
		var title = "完善客户资料";
		var id = "consultant_client" + this.clientKey;

		create_model( url, title, id, 8999, ()=>{this.request_client_info();} );
		open_model( id, true );
	}

	private showOrHideDetailed( rel:string = 'hide' ):void
	{
		var show = this._table.find( "tr[rel='" + rel + "']:first" ).visible();
		this.detailed( !show );
	}

}